package com.lotusfall.mysport.controller;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.amap.api.maps.model.LatLng;
import com.lotusfall.mysport.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class TrackController {

    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
    private static final int SUCCESS = 665;
    private static final int FALL = 894;
    public static int flag = 0;
    public static int regular = 0;
    public static String cookie = null;
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10,TimeUnit.SECONDS)
            .writeTimeout(10,TimeUnit.SECONDS)
            .cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                    cookieStore.put(httpUrl.host(), list);
                    cookieStore.put(HttpUrl.parse("http://192.168.125.119:8080/").toString(), list);
                    for(Cookie cookie:list){
                        System.out.println("cookie Name:"+cookie.name());
                        System.out.println("cookie Path:"+cookie.path());
                        System.out.println("cookie:"+ cookie);
                    }
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                    List<Cookie> cookies = cookieStore.get(httpUrl.host());
                    System.out.println("cookie:"+ cookies);
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }
            })
            .build();

    public void saveTrack(List<LatLng> points, double dist, View view) {
//        SharedPreferences setting = view.getContext().getSharedPreferences("setting", 0);
//        cookie = setting.getString("cookie",cookie);

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        double kcal = 60 * dist * 1.036 * 0.001;  // 根据公式计算消耗卡路里
        for (LatLng latLng : points){

            try {
                JSONArray ll = new JSONArray();
                ll.put(latLng.latitude);
                ll.put(latLng.longitude);
                jsonArray.put(ll);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // 1个数组参数
        System.out.println(jsonArray);
        try {
            jsonObject.put("tags", jsonArray);
            jsonObject.put("startTime",System.currentTimeMillis());
            jsonObject.put("dist",dist);
            jsonObject.put("kcal",kcal);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // 3个字符串参数
        String data = jsonObject.toString();
        // 构造请求体
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), data);
        Request request = new Request.Builder()
                .url("http://192.168.125.119:8080/updateTrack")
                .header("Cookie",UserController.cookie)
                .post(body)
                .build();
        // 向服务器异步请求数据
        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Log.i("track_saving", "失败");
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                ResponseBody body = response.body();
                Log.i("track_saving", "返回数据：" + body.string());
            }
        });
    }

    public JSONArray getTrackList(){
        final JSONArray[] jsonArray = new JSONArray[1];
        Runnable runnable = new Runnable(){
            @Override
            public void run() {

                Request request = new Request.Builder()
                        .get()
                        .url("http://192.168.125.119:8080/getTrackList")
                        .header("Cookie",UserController.cookie)
                        .build();
                try {
                    Response response = okHttpClient.newCall(request).execute(); //获取服务器返回的数据
                    String responseData = response.body().string();
                    jsonArray[0] = new JSONArray(responseData);

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        try {
            thread.join();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(jsonArray[0] !=null)return jsonArray[0];
        else return new JSONArray();
    }

    public List<LatLng> getTrackDetail(Long trackId) throws InterruptedException {
        List<LatLng> points = new ArrayList<>();
        final JSONArray[] jsonArray = new JSONArray[1];
        Runnable runnable = new Runnable(){
            @Override
            public void run() {

                Request request = new Request.Builder()
                        .get()
                        .url("http://192.168.125.119:8080/getTrack?trackId=" + trackId)
                        .header("Cookie",UserController.cookie)
                        .build();
                try {
                    Response response = okHttpClient.newCall(request).execute(); //获取服务器返回的数据
                    String responseData = response.body().string();
                    jsonArray[0] = new JSONArray(responseData);
                    System.out.println("0:" + jsonArray[0].get(0));

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        thread.join();
        for(int i = 0;i < jsonArray[0].length();i++){
            try {
                JSONArray llArray = (JSONArray) jsonArray[0].get(i);
                LatLng latLng = new LatLng(Double.parseDouble(llArray.get(0).toString()),Double.parseDouble(llArray.get(1).toString()));
                points.add(latLng);


            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        return points;
    }

}
